<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * Channel Protocol Mapping Management - 渠道协议关联管理
 *
 * 功能：管理渠道与协议的关联关系，支持四种协议类型的配置
 * 版本：1.0.0
 *
 * Website: https://www.anypay.com
-->

<template>
  <div class="anypay-apple-list-page">
    <div class="anypay-apple-page-header">
      <h1>渠道协议关联管理</h1>
      <p>查看各个渠道的协议信息，基于约定自动关联相应的协议（服务商、直连商户、子商户三种模式），只读模式</p>
    </div>

    <!-- 搜索区域 -->
    <div class="anypay-apple-card anypay-apple-mb-6">
      <a-card>
        <div class="search-container standard">
          <!-- 渠道 -->
          <div class="search-field">
            <label class="search-label">渠道:</label>
            <a-select
              v-model:value="searchForm.channelCode"
              placeholder="请选择渠道"
              class="search-select-large"
              allowClear
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option
                v-for="channel in allChannels"
                :key="channel.channelCode"
                :value="channel.channelCode"
              >
                <div style="display: flex; align-items: center;">
                  <img
                    v-if="channel.iconUrl"
                    :src="channel.iconUrl"
                    :alt="channel.channelName"
                    style="width: 16px; height: 16px; margin-right: 8px;"
                    @error="handleIconError"
                  />
                  <span>{{ channel.channelName }}</span>
                </div>
              </a-select-option>
            </a-select>
          </div>

          <!-- 状态 -->
          <div class="search-field">
            <label class="search-label">状态:</label>
            <a-select
              v-model:value="searchForm.enabled"
              placeholder="请选择状态"
              class="search-select"
              allowClear
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option :value="true">启用</a-select-option>
              <a-select-option :value="false">禁用</a-select-option>
            </a-select>
          </div>

          <!-- 操作按钮 -->
          <div class="search-actions">
            <a-button type="primary" @click="handleSearch" class="search-btn">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset" class="search-btn">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 关联表格 -->
    <div class="anypay-apple-card">
      <a-card>
        <div class="anypay-apple-table anypay-apple-toolbar">
          <AnyTable
            ref="mappingTable"
            :tableColumns="mappingColumns"
            :dataLoader="loadMappingData"
            :searchParams="searchParams"
            :tableScroll="{ x: 'max-content' }"
            :autoLoad="true"
            tableRowKey="channelCode"
            @loadComplete="handleLoadComplete"
          >
            <template #tableToolbar>
              <a-space :size="12">
                <a-button @click="handleRefreshData">
                  <ReloadOutlined /> 刷新数据
                </a-button>
                <a-button @click="handleTestLookup">
                  <SearchOutlined /> 测试协议查找
                </a-button>
              </a-space>
            </template>
            <template #tableCell="{ column, record }">
              <template v-if="column.key === 'channelIcon'">
                <img
                  v-if="record.iconUrl"
                  :src="record.iconUrl"
                  :alt="record.channelName"
                  style="width: 32px; height: 32px; object-fit: contain;"
                  @error="handleIconError"
                />
              </template>
              <template v-else-if="column.key === 'channelName'">
                <div>
                  <div style="font-weight: 500;">{{ record.channelName }}</div>
                  <div style="font-size: 12px; color: #666;">{{ record.channelCode }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'provider'">
                <div>
                  <div style="font-weight: 500; margin-bottom: 4px;">
                    <a-tag :color="getProtocolStatusColor(record.protocols.provider)">
                      {{ getProtocolDisplayName(record.protocols.provider) }}
                    </a-tag>
                  </div>
                  <div style="font-size: 11px; color: #8c8c8c; line-height: 1.3;">
                    {{ record.protocols.provider }}
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'directMerchant'">
                <div>
                  <div style="font-weight: 500; margin-bottom: 4px;">
                    <a-tag :color="getProtocolStatusColor(record.protocols.directMerchant)">
                      {{ getProtocolDisplayName(record.protocols.directMerchant) }}
                    </a-tag>
                  </div>
                  <div style="font-size: 11px; color: #8c8c8c; line-height: 1.3;">
                    {{ record.protocols.directMerchant }}
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'subMerchant'">
                <div>
                  <div style="font-weight: 500; margin-bottom: 4px;">
                    <a-tag :color="getProtocolStatusColor(record.protocols.subMerchant)">
                      {{ getProtocolDisplayName(record.protocols.subMerchant) }}
                    </a-tag>
                  </div>
                  <div style="font-size: 11px; color: #8c8c8c; line-height: 1.3;">
                    {{ record.protocols.subMerchant }}
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'onboarding'">
                <div>
                  <div style="font-weight: 500; margin-bottom: 4px;">
                    <a-tag :color="getProtocolStatusColor(record.protocols.onboarding)">
                      {{ getProtocolDisplayName(record.protocols.onboarding) }}
                    </a-tag>
                  </div>
                  <div style="font-size: 11px; color: #8c8c8c; line-height: 1.3;">
                    {{ record.protocols.onboarding }}
                  </div>
                </div>
              </template>
              <template v-else-if="column.key === 'enabled'">
                <a-tag :color="record.enabled ? 'green' : 'red'">
                  {{ record.enabled ? '启用' : '禁用' }}
                </a-tag>
              </template>
              <template v-else-if="column.key === 'actions'">
                <div class="anypay-apple-actions">
                  <a-space>
                    <a-button type="link" @click="handleView(record)">
                      <EyeOutlined />查看详情
                    </a-button>
                    <a-button type="link" @click="handleViewProtocolInfo(record)">
                      <SearchOutlined />查看
                    </a-button>
                    <a-dropdown placement="bottomRight">
                      <a-button type="link" size="small">
                        <MoreOutlined />
                        更多
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click="handleCopyConfig(record)">
                            <CopyOutlined />
                            复制协议信息
                          </a-menu-item>
                          <a-menu-item @click="handleTestChannelProtocols(record)">
                            <ExperimentOutlined />
                            测试协议查找
                          </a-menu-item>
                          <a-menu-item @click="handleRefreshChannel(record)">
                            <ReloadOutlined />
                            刷新协议
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </a-space>
                </div>
              </template>
            </template>
          </AnyTable>
        </div>
      </a-card>
    </div>

    <!-- 查看详情抽屉 -->
    <a-drawer
      v-model:visible="showViewDrawer"
      title="渠道协议关联详情"
      width="800"
      :footer-style="{ textAlign: 'right' }"
    >
      <div v-if="selectedMapping">
        <a-descriptions bordered :column="2">
          <a-descriptions-item label="渠道代码">
            <a-tag color="blue">{{ selectedMapping.channelCode }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="渠道名称">
            {{ selectedMapping.channelName }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="selectedMapping.enabled ? 'green' : 'red'">
              {{ selectedMapping.enabled ? '启用' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ selectedMapping.updateTime }}
          </a-descriptions-item>
          <a-descriptions-item label="协议查找约定" :span="2">
            基于getProtocolByConvention函数自动关联各种协议类型
          </a-descriptions-item>
          <a-descriptions-item label="描述" :span="2">
            {{ selectedMapping.description }}
          </a-descriptions-item>
        </a-descriptions>

        <a-divider orientation="left">协议关联信息</a-divider>

        <a-list :dataSource="getProtocolConfigList(selectedMapping)" size="small">
          <template #renderItem="{ item }">
            <a-list-item>
              <template #actions>
                <a-button type="link" size="small" @click="viewProtocolDetails(item.protocolId)">
                  查看协议
                </a-button>
              </template>
              <a-list-item-meta>
                <template #title>
                  <a-space>
                    <span>{{ item.typeName }}</span>
                    <a-tag :color="item.color">{{ item.protocolName }}</a-tag>
                  </a-space>
                </template>
                <template #description>
                  协议ID: {{ item.protocolId }}
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </a-drawer>

    <!-- 协议详情抽屉 -->
    <ProtocolInfoDrawer
      v-model:visible="showProtocolDetails"
      :protocol="selectedProtocolForDetails"
      :is-default="false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  EyeOutlined,
  MoreOutlined,
  SearchOutlined,
  ReloadOutlined,
  CopyOutlined,
  ExperimentOutlined
} from '@ant-design/icons-vue'
import {
  getAllChannelProtocolMappings,
  type ChannelProtocolMapping
} from '../../../mock/channel-protocol-mapping'
import { paymentChannels } from '../../../mock/channels'
import { protocol3Manager } from '../../../mock/protocol3-manager'
import { initializeSampleData } from '../../../mock/protocol3-sample-data'
import type { MerchantChannelConfig3, QRCodeConfig } from '../../../types/protocol3-types'
import type { AnyProtocol } from '../../../types/channel-config-protocol'
import ProtocolInfoDrawer from '../../../components/ProtocolInfoDrawer.vue'
import AnyTable from '@/components/AnyTable.vue'

// 响应式数据
const loading = ref(false)
const allMappings = ref<ChannelProtocolMapping[]>([])
const allChannels = ref(paymentChannels)
const mappingTable = ref()

// 搜索表单
const searchParams = reactive({
  channelCode: '',
  enabled: null
})

const searchForm = reactive({
  channelCode: '',
  enabled: null
})

// 抽屉状态
const showViewDrawer = ref(false)
const selectedMapping = ref<ChannelProtocolMapping | null>(null)

const showProtocolDetails = ref(false)
const selectedProtocolForDetails = ref<AnyProtocol | null>(null)

// 协议数据
const availableProtocols = ref<(MerchantChannelConfig3 | QRCodeConfig | any)[]>([])

// 表格列定义
const mappingColumns = [
  {
    title: '渠道图标',
    key: 'channelIcon',
    width: 80,
    align: 'center'
  },
  {
    title: '渠道信息',
    key: 'channelName',
    width: 150
  },
  {
    title: '服务商协议',
    key: 'provider',
    width: 200,
    ellipsis: true
  },
  {
    title: '直连商户协议',
    key: 'directMerchant',
    width: 200,
    ellipsis: true
  },
  {
    title: '子商户协议',
    key: 'subMerchant',
    width: 200,
    ellipsis: true
  },
  {
    title: '进件协议',
    key: 'onboarding',
    width: 200,
    ellipsis: true
  },
  {
    title: '状态',
    key: 'enabled',
    width: 80,
    align: 'center'
  },
  {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'center',
    fixed: 'right'
  }
]


// 获取协议显示名称
const getProtocolDisplayName = (protocolId: string) => {
  if (protocolId === 'DEFAULT_PROTOCOL_FALLBACK_001') {
    return '默认兜底协议'
  }

  const protocol = availableProtocols.value.find(p => p.protocolId === protocolId)
  return protocol ? protocol.name : '未知协议'
}

// 获取协议状态颜色
const getProtocolStatusColor = (protocolId: string) => {
  if (protocolId === 'DEFAULT_PROTOCOL_FALLBACK_001') {
    return 'orange' // 兔底协议使用橙色
  }

  const protocol = availableProtocols.value.find(p => p.protocolId === protocolId)
  if (protocol) {
    return protocol.enabled ? 'green' : 'red'
  }

  return 'default'
}

// 获取协议配置列表（用于详情展示）
const getProtocolConfigList = (mapping: ChannelProtocolMapping) => {
  const configs = []

  if (mapping.protocols.provider) {
    configs.push({
      typeName: '服务商协议',
      protocolId: mapping.protocols.provider,
      protocolName: getProtocolDisplayName(mapping.protocols.provider),
      color: getProtocolStatusColor(mapping.protocols.provider)
    })
  }

  if (mapping.protocols.directMerchant) {
    configs.push({
      typeName: '直连商户协议',
      protocolId: mapping.protocols.directMerchant,
      protocolName: getProtocolDisplayName(mapping.protocols.directMerchant),
      color: getProtocolStatusColor(mapping.protocols.directMerchant)
    })
  }

  if (mapping.protocols.subMerchant) {
    configs.push({
      typeName: '子商户协议',
      protocolId: mapping.protocols.subMerchant,
      protocolName: getProtocolDisplayName(mapping.protocols.subMerchant),
      color: getProtocolStatusColor(mapping.protocols.subMerchant)
    })
  }

  if (mapping.protocols.onboarding) {
    configs.push({
      typeName: '进件协议',
      protocolId: mapping.protocols.onboarding,
      protocolName: getProtocolDisplayName(mapping.protocols.onboarding),
      color: getProtocolStatusColor(mapping.protocols.onboarding)
    })
  }

  return configs
}

// AnyTable数据加载器
const loadMappingData = async (params: any) => {
  try {
    console.log('渠道协议关联数据加载器被调用，参数:', params)

    // 确保数据已初始化
    if (allMappings.value.length === 0) {
      console.log('数据未初始化，等待初始化完成...')
      await initializeData()
    }

    // 获取所有关联数据（已包含默认配置逻辑）
    const allData = getAllChannelProtocolMappings()
    console.log('获取到的所有关联数据:', allData)

    // 应用搜索过滤
    let filtered = [...allData]

    // 按渠道过滤
    if (params.channelCode) {
      filtered = filtered.filter(m => m.channelCode === params.channelCode)
    }

    // 按状态过滤
    if (params.enabled !== null && params.enabled !== undefined) {
      filtered = filtered.filter(m => m.enabled === params.enabled)
    }

    // 分页处理
    const total = filtered.length
    const startIndex = (params.pageNumber - 1) * params.pageSize
    const endIndex = startIndex + params.pageSize
    const records = filtered.slice(startIndex, endIndex)

    console.log('过滤后的数据:', filtered)
    console.log('分页后的数据:', records)

    return {
      records,
      total,
      pageNumber: params.pageNumber,
      pageSize: params.pageSize
    }
  } catch (error) {
    console.error('加载渠道协议关联数据失败:', error)
    return {
      records: [],
      total: 0,
      pageNumber: 1,
      pageSize: 10
    }
  }
}

// 表格加载完成回调
const handleLoadComplete = () => {
  console.log('渠道协议关联数据加载完成')
}

// 初始化数据
const initializeData = async () => {
  loading.value = true
  try {
    console.log('开始初始化渠道协议关联数据...')

    // 初始化协议数据
    await initializeSampleData()
    console.log('协议数据初始化完成')

    // 等待一下确保数据完全加载
    await new Promise(resolve => setTimeout(resolve, 100))

    // 获取所有协议
    availableProtocols.value = protocol3Manager.getAllProtocols()
    console.log('获取到协议数量:', availableProtocols.value.length)

    // 获取所有关联数据
    allMappings.value = getAllChannelProtocolMappings()
    console.log('获取到关联数据数量:', allMappings.value.length)

    console.log('渠道协议关联数据初始化完成', {
      totalMappings: allMappings.value.length,
      totalProtocols: availableProtocols.value.length
    })

    // 确保表格组件存在后再刷新
    if (mappingTable.value) {
      await nextTick()
      mappingTable.value.refreshTable(true)
    }
  } catch (error) {
    console.error('初始化渠道协议关联数据失败:', error)
    message.error('初始化渠道协议关联数据失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  Object.assign(searchParams, {
    channelCode: searchForm.channelCode,
    enabled: searchForm.enabled
  })

  mappingTable.value?.refreshTable(true)
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    channelCode: '',
    enabled: null
  })

  Object.assign(searchParams, {
    channelCode: '',
    enabled: null
  })

  mappingTable.value?.refreshTable(true)
}

// 刷新数据
const handleRefreshData = () => {
  initializeData()
  mappingTable.value?.refreshTable()
  message.success('数据刷新成功')
}

// 测试协议查找
const handleTestLookup = () => {
  const testCases = [
    { protocolCode: 'CHANNEL_PROTOCOL_WXPAY', configType: 'PROVIDER' },
    { protocolCode: 'CHANNEL_PROTOCOL_WXPAY', configType: 'DIRECT_MERCHANT' },
    { protocolCode: 'CHANNEL_PROTOCOL_ALIPAY', configType: 'PROVIDER' },
    { protocolCode: 'CHANNEL_PROTOCOL_UNKNOWN', configType: 'PROVIDER' },
  ]

  console.log('\n=== 协议查找测试 ===')
  testCases.forEach(({ protocolCode, configType }) => {
    const result = protocol3Manager.getProtocolByConvention(protocolCode, configType)
    console.log(`${protocolCode} + ${configType} -> ${result}`)
  })

  message.success('协议查找测试完成，请查看控制台输出')
}

// 查看详情
const handleView = (record: ChannelProtocolMapping) => {
  selectedMapping.value = record
  showViewDrawer.value = true
}

// 查看协议信息
const handleViewProtocolInfo = (record: ChannelProtocolMapping) => {
  const protocolInfo = {
    channelCode: record.channelCode,
    channelName: record.channelName,
    protocols: record.protocols,
    protocolDetails: record.protocolInfo
  }

  console.log('渠道协议信息:', protocolInfo)
  message.success('协议信息已输出到控制台')
}

// 刷新渠道协议
const handleRefreshChannel = (record: ChannelProtocolMapping) => {
  // 重新生成该渠道的协议关联
  const protocolCode = record.channelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')

  const refreshedProtocols = {
    provider: protocol3Manager.getProtocolByConvention(protocolCode, 'PROVIDER'),
    directMerchant: protocol3Manager.getProtocolByConvention(protocolCode, 'DIRECT_MERCHANT'),
    subMerchant: protocol3Manager.getProtocolByConvention(protocolCode, 'SUB_MERCHANT')
  }

  console.log(`渠道 ${record.channelName} 的协议关联已刷新:`, refreshedProtocols)
  message.success(`渠道 ${record.channelName} 的协议关联已刷新`)

  // 刷新表格数据
  mappingTable.value?.refreshTable()
}

// 复制配置
const handleCopyConfig = async (record: ChannelProtocolMapping) => {
  try {
    await navigator.clipboard.writeText(JSON.stringify(record.protocols, null, 2))
    message.success('协议配置已复制到剪贴板')
  } catch (error) {
    message.error('复制失败')
  }
}

// 测试渠道协议查找
const handleTestChannelProtocols = (record: ChannelProtocolMapping) => {
  const protocolCode = record.channelCode.replace('CHANNEL_IF_', 'CHANNEL_PROTOCOL_')

  console.log(`\n=== 渠道 ${record.channelName} 协议查找测试 ===`)

  const configTypes = ['PROVIDER', 'DIRECT_MERCHANT', 'SUB_MERCHANT']
  configTypes.forEach(configType => {
    const result = protocol3Manager.getProtocolByConvention(protocolCode, configType)
    console.log(`${protocolCode} + ${configType} -> ${result}`)
  })

  message.success(`渠道 ${record.channelName} 的协议查找测试完成，请查看控制台输出`)
}

// 查看协议详情
const viewProtocolDetails = (protocolId: string) => {
  const protocol = availableProtocols.value.find(p => p.protocolId === protocolId)
  if (protocol) {
    // 转换为 AnyProtocol 格式 - 根据协议类型添加必需属性
    const baseProtocol = {
      protocolId: protocol.protocolId,
      protocolType: protocol.protocolType as any,
      name: protocol.name,
      version: protocol.version,
      description: protocol.description,
      uiConfig: {
        layout: 'vertical',
        labelWidth: 120
      },
      metadata: protocol.metadata || {},
      enabled: protocol.enabled,
      configSections: protocol.configSections || []
    }

    // 根据协议类型添加特定属性
    let anyProtocol: AnyProtocol
    if (protocol.protocolType === 'MERCHANT_CHANNEL_CONFIG_V3') {
      anyProtocol = {
        ...baseProtocol,
        channelCode: protocol.channelCode || '',
        channelName: protocol.channelName || ''
      } as any
    } else {
      anyProtocol = baseProtocol as any
    }

    selectedProtocolForDetails.value = anyProtocol
    showProtocolDetails.value = true
  } else {
    message.error(`未找到协议ID为 "${protocolId}" 的协议`)
  }
}

// 处理图标加载错误
const handleIconError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 组件挂载时初始化数据
onMounted(async () => {
  await initializeData()
})

// 监听路由变化，确保数据正确加载
const route = useRoute()

// 监听路由变化
watch(() => route.path, async (newPath: string) => {
  if (newPath.includes('channel-protocol-mapping')) {
    console.log('路由变化，重新初始化数据')
    await initializeData()
  }
}, { immediate: true })
</script>

<style scoped>
@import '../common/list-page.css';

/* 页面特定样式 */
.ant-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

:deep(.ant-table-fixed-left) {
  z-index: 2;
}

:deep(.ant-table-fixed-right) {
  z-index: 1;
}

:deep(.ant-select) {
  min-width: 120px;
}

:deep(.ant-descriptions-item-content) {
  word-break: break-all;
}
</style>